package com.example.handler;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.example.result.ErrorEnum;
import com.example.result.ErrorResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName MyUrlBlockHandler
 * @Description TODO
 * @Author: XMK
 * @Date: 2020/5/7 11:04
 * @Version: 1.0
 */
@Component
@Slf4j
public class MyUrlBlockHandler implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
        if (e instanceof FlowException) {
            log.warn("触发了流控");
            wrapperResponse(httpServletResponse, ErrorEnum.FLOW_RULE_ERR);
        } else if (e instanceof DegradeException) {
            log.warn("触发了降级");
            wrapperResponse(httpServletResponse, ErrorEnum.DEGRADE_RULE_ERR);
        } else if (e instanceof SystemBlockException) {
            log.warn("触发了系统规则");
            wrapperResponse(httpServletResponse, ErrorEnum.SYS_RULE_ERR);
        } else if (e instanceof AuthorityException) {
            log.warn("触发了认证规则");
            wrapperResponse(httpServletResponse, ErrorEnum.AUTH_RULE_ERR);
        } else if (e instanceof ParamFlowException) {
            log.warn("触发了热点参数流控");
            wrapperResponse(httpServletResponse, ErrorEnum.HOT_PARAM_FLOW_RULE_ERR);
        }
    }

    private void wrapperResponse(HttpServletResponse response, ErrorEnum errorEnum) throws IOException {
        response.setStatus(500);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");

        ObjectMapper mapper = new ObjectMapper();
        String res = mapper.writeValueAsString(new ErrorResult(errorEnum));
        response.getWriter().write(res);
    }
}
